# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify, make_response, render_template, flash, redirect, url_for, session, escape, g
from models.database import db_session
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.auth import Auth, AuthUser, login_required, logout
from models.sa import get_user_class
import commands,os,re,sys,shutil
from werkzeug import secure_filename
reload(sys)
sys.setdefaultencoding('utf-8')
app = Flask(__name__)
app.config.from_pyfile('app.cfg')

# Instantiate DB
db = SQLAlchemy(app)

## Set SQL Alchemy to automatically tear down
@app.teardown_request
def shutdown_session(exception=None):
    db_session.remove()

# Instantiate authentication
auth = Auth(app, login_url_name='login')
User = get_user_class(db.Model)

UPLOAD_FOLDER = '/file/'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','tar.gz','gz','sls'])

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


grouplist = ['NJ-S-FC','NJ-Q-FC','NJ-M-FC','NJ-L-FC','NJ-K-FC','NJ-H-FC','NJ-R-FC','NJ-4-FC','NJ-5-FC','NJ-6-FC','NJ-4-FSCS','NJ-5-FSCS','NJ-6-FSCS','NJ-S-FSCS','NJ-M-FSCS','NJ-Q-FSCS','NJ-L-FSCS','NJ-K-FSCS','NJ-H-FSCS','NJ-R-FSCS','FSCS','FC']
cpisapplist = ['cpisapp.cpisapp','cpisapp.amr']
cpisslslist = ['fcinit.fcinit','fcservice.service','CPISWEB.cpisweb','fscsinit.fscsinit','fcservice.service','CPISFSCS.node4','CPISFSCS.node5','CPISFSCS.node6','CPISFSCS.nodeS','CPISFSCS.nodeM','CPISFSCS.nodeQ','CPISFSCS.nodeL','CPISFSCS.nodeK','CPISFSCS.nodeH','CPISFSCS.nodeR']


def index():
    return render_template('index.html')

##login methods

def login():
    if request.method == 'POST':
        username = request.form['username']
        user = User.query.filter(User.username==username).first()
        if user is not None:
            # Authenticate and log in!
            if user.authenticate(request.form['password']):
                session['username'] = request.form['username']
                return redirect(url_for('home'))
            else:
                flash('Incorrect password. Please try again or mailto cpis-opt@chinacache.com')
                return render_template('login.html')
        else:
            flash('Incorrect username. Please try again or mailto cpis-opt@chinacache.com')
            return render_template('login.html')
    return render_template('login.html')


@login_required()
def home():
    ##Dump variables in templates
    return render_template('home.html')

@login_required()
def sc():
    return render_template('sc.html',grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)

@login_required()
def sc1():
    return render_template('sc1.html',grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)


@login_required()
def grains():
    grains=os.popen('salt \* grains.item type').read()
    return render_template('grains.html',grains=grains)

@app.route('/cpis.html')
def jquery():
    return render_template('cpis.html')

@login_required()
def tongji():
   accept=os.popen('ls -l /var/cache/salt/master/minions/|wc -l').read()
   unaccept=os.popen("salt-key |sed -n '/Unaccepted Keys/,/Rejected Keys/p'|wc -l ").read()
   down=os.popen("salt-run manage.status |sed -n '/down/,/up/p'|wc -l").read()
   return render_template('tongji.html',accept=accept,unaccept=unaccept,down=down)


@login_required()
def vim():
   return render_template('vim.html')

@login_required()
def mvim():
   return render_template('mvim.html')

@login_required()
def cpisfile():
   return render_template('file.html')
@app.route('/about.html')
def about():
   return render_template('about.html')

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/upfile', methods=['GET', 'POST'])
def upfile():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        cmd=os.popen('ls -lh /file|sed 1d').read()
        cmd = '\n%s' % cmd
        print cmd
        return render_template('file.html',cmd=cmd)

namefile=''
@app.route('/cpisvim',methods=['GET','POST'])
def cpisvim():
    if request.method == 'POST':
        name=request.form['name']
        global namefile
        namefile=name
        info=os.popen('cat '+name).read()
        info = '\n%s' %  info
        print namefile
        return render_template('vim.html', info=info)

file=''
@app.route('/cpismvim',methods=['GET','POST'])
def cpismvim():
    if request.method == 'POST':
        name=request.form['name']
        host=request.form['host']
        global file,name
        file=name
        cmd='salt ' + host +' cmd.run '  + "' cat " +  name + "'" + ' |grep -v ' + "'"+host+':'+"'"
        info=os.popen(cmd).read()
        info = '\n%s' %  info
        print file
        return render_template('mvim.html', info=info)

@app.route('/cpismsave',methods=['GET','POST'])
def cpismsave():
    if request.method == 'POST':
        global file
        NAME=request.form['name']
        host=request.form['host']
        info = '%s' % NAME
        print 'file is  %s'% NAME
        object=commands.getoutput('date +%N')        
        filelog=open(object,'w')
        filelog.write(info)
        filelog.close()
        info=os.popen('cat %s' % object).read()
        mv=shutil.move(object,"/srv/salt/File/")
        scp='salt ' + host + ' cp.get_file salt://File/'+ object + ' ' + name
        jj=os.popen(scp)
        print name,scp
        return render_template('mvim.html', info=info)

@app.route('/cpissave',methods=['GET','POST'])
def cpissave():
    if request.method == 'POST':
        global namefile
        name=request.form['name']
        info = '%s' % name
        print 'start\n %s \nend'%info
        print 'file is  %s'% namefile
        filelog=open(namefile,'w')
        filelog.write(info)
        filelog.close() 
        info=os.popen('cat %s' % namefile).read()
        return render_template('vim.html', info=info)

def user_create():
    if request.method == 'POST':
        username = request.form['username']
        if User.query.filter(User.username==username).first():
            return 'User already exists.'
        password = request.form['password']
        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('user_create.html')

def logout_view():
    user_data = logout()
    if user_data is None:
        msg = 'No user to log out.'
        return render_template('logout.html', msg=msg)
    else:
        msg = 'Bye Bye {0}.'.format(user_data['username'])
        return render_template('logout.html', msg=msg)


# URLs
app.add_url_rule('/', 'index', index)
app.add_url_rule('/login/', 'login', login, methods=['GET', 'POST'])
app.add_url_rule('/home/', 'home', home)
app.add_url_rule('/create/', 'user_create', user_create, methods=['GET', 'POST'])
app.add_url_rule('/logout/', 'logout', logout_view)
app.add_url_rule('/sc/','sc',sc)
app.add_url_rule('/sc1/','sc1',sc1)
app.add_url_rule('/grains/','grains',grains)
app.add_url_rule('/tongji/','tongji',tongji)
app.add_url_rule('/vim/','vim',vim,)
app.add_url_rule('/mvim/','mvim',mvim,)
app.add_url_rule('/file/','cpisfile',cpisfile,)

@app.route('/linux',methods=['GET','POST'])
def  sharekk():
     if request.method == 'POST':
         host   = request.form['host']
         cmd   = request.form['cmd']
         if re.search('reboot',cmd)  or  re.search('shutdown',cmd) or re.search('init',cmd) or re.search('halt',cmd) or re.search('passwd',cmd) or re.search('rm',cmd) or re.search('poweroff',cmd):
            return 'you......'
         else:
#            cpiscmd = 'salt ' + host +' cmd.run ' + "'" + cmd + "'"
            cpiscmd = 'salt %s cmd.run \'%s\' ' %(host,cmd)
            shencan = str(cpiscmd)
            res   =os.popen(shencan).read().replace('[1;32m','').replace('[31m','').replace('[0m','').replace('[0;33;1m','').replace('[0;31;1m','').replace('[7;30;1m','').decode('gbk','ignore').encode('utf-8')
#            res   =commands.getoutput(shencan).replace('[1;32m','').replace('[31m','').replace('[0m','').replace('[0;33;1m','').replace('[0;31;1m','').replace('[7;30;1m','')
         print shencan,res
         print type(cpiscmd),type(shencan),type(res),type(grouplist),type(cpisapplist),type(cpisslslist)
     return render_template('sc1.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)

@app.route('/linux2',methods=['GET','POST'])
def  sharek():
     if request.method == 'POST':
         cmd   = request.form['cpis']
         if re.search('reboot',cmd)  or  re.search('shutdown',cmd) or re.search('init',cmd) or re.search('halt',cmd) or re.search('passwd',cmd) or re.search('rm',cmd) or re.search('poweroff',cmd):
            return 'you......'
         else:
            res   =os.popen(cmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').replace('[0;33;1m','').replace('[0;31;1m','').replace('[7;30;1m','').decode('gbk','ignore').encode('utf-8')
         print cmd 
     return render_template('sc1.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)

@app.route('/linux3',methods=['GET','POST'])
def  sharekkk():
     if request.method == 'POST':
         group   = request.form['select']
         cmd   = request.form['cmd']
         if re.search('reboot',cmd)  or  re.search('shutdown',cmd) or re.search('init',cmd) or re.search('halt',cmd) or re.search('passwd',cmd) or re.search('rm',cmd) or re.search('poweroff',cmd):
            return 'you......'
         else:
            cpiscmd = 'salt -N ' + group +' cmd.run ' + "'" + cmd + "'"
            res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').replace('[0;33;1m','').replace('[0;31;1m','').replace('[7;30;1m','').decode('gbk','ignore').encode('utf-8')
         print cpiscmd
     return render_template('sc1.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)




@app.route('/linux4',methods=['GET','POST'])
def  sharekkkk():
     if request.method == 'POST':
         group   = request.form['select']
         app   = request.form['select2']
         cpiscmd = 'salt -N ' + group + ' ' + app
         res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').decode('gbk','ignore').encode('utf-8')
         print cpiscmd
     return render_template('sc.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)


@app.route('/linux5',methods=['GET','POST'])
def  sharekkkkk():
     if request.method == 'POST':
         group   = request.form['select']
         sls   = request.form['select2']
         cpiscmd = 'salt -N ' + group + ' state.sls ' + sls
         res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').decode('gbk','ignore').encode('utf-8')
         print cpiscmd
     return render_template('sc.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)

@app.route('/linux6',methods=['GET','POST'])
def  cpis():
     if request.method == 'POST':
         host   = request.form['host']
         sls   = request.form['select2']
         cpiscmd = 'salt ' + host + ' state.sls ' + sls
         res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').decode('gbk','ignore').encode('utf-8')
         print cpiscmd
     return render_template('sc.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)

@app.route('/linux7',methods=['GET','POST'])
def  cpis1():
     if request.method == 'POST':
         host   = request.form['host']
         app   = request.form['select2']
         cpiscmd = 'salt ' + host + ' ' + app
         res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').decode('gbk','ignore').encode('utf-8')
         print cpiscmd
     return render_template('sc.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)


@app.route('/linux8',methods=['GET','POST'])
def  cpis2():
     if request.method == 'POST':
         host   = request.form['tagsinput']
         jb   = request.form['cpis']
         cpiscmd = 'salt -L  \'%s\' cmd.run \'%s\' ' %(host,jb)
         res   =os.popen(cpiscmd).read().replace('[1;32m','').replace('[31m','').replace('[0m','').replace('[0;33;1m','').replace('[0;31;1m','').replace('[7;30;1m','').decode('gbk','ignore').encode('utf-8')
         print host,cpiscmd
     return render_template('sc1.html',name=res,grouplist=grouplist,cpisapplist=cpisapplist,cpisslslist=cpisslslist)



# Secret key needed to use sessions.
app.secret_key = 'mysecretkey'
  
if __name__ == "__main__":
    try:
        open('/tmp/app.db')
    except IOError:
        db.create_all()
    app.run(debug=True,host='127.0.0.1',port=1023)
